package hk.cic.demointegrationapp;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cily.utils.base.HttpUtils;
import com.cily.utils.log.L;
import com.mfrs.HttpU;
import com.mfrs.demos.TestActivity;

import org.apache.http.client.HttpClient;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

import hk.cic.cwrs.bio.integration.log.IBioService;

/**
 * user:cily
 * time:2017/8/6
 * desc:
 */

public class IcService extends Service {
    ResultLogListener resultLogListener = new ResultLogListener();

    boolean bLog = false;
    IBioService ibioService = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Handler mHandler;

    @Override
    public void onCreate() {
        super.onCreate();

        mHandler = new Handler(getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MSG_GET_WORKER_DETAILES_FAILED){
                    App.getApp().showToast("获取员工信息失败，请重试");
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ResultLog");
        registerReceiver(resultLogListener, intentFilter);

        IntentFilter ftStatus = new IntentFilter();
        ftStatus.addAction("Status");

        try {
            bindService(new Intent(this, IBioService.class), conLog, BIND_AUTO_CREATE);
        } catch (Exception e) {
            L.printException(e);
        }
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(resultLogListener);

        if (bLog == true) {
            unbindService(conLog);
            bLog = false;
        }

        super.onDestroy();
    }

    public class ResultLogListener extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("ResultLog")) {
                intent.getExtras();
                final String strDetail = intent.getStringExtra("resultLog");
                IcCardBean bean = com.alibaba.fastjson.JSONObject.parseObject(strDetail,IcCardBean.class);
                if (bean != null){
                    //判断 是查询记录还是 打卡
                   // String res = new HttpPost().HttpRequestAPI("http://47.90.73.137:8090/api/values","GET", "");
                    if(getIsFace()==1) {
                       openFaceCheckResulterView(context, bean.getCWRNo());
                        //  getWorkerDetails(bean.getSessionID(),bean.getCWRNo());
                    } if(getIsFace() == 0) {
                        //查询记录
                        openCheckInOutView(context, bean.getCWRNo());
                    } else {

                        justCheckResulterView(context, bean.getCWRNo());
                    }
                }else{
                    App.getApp().showToast("json解析出错：" + strDetail);
                }
                L.i("IcService", "监听到的消息：" + strDetail);

                //TODO 监听到消息后，跳转到MainActivity页面里，并把卡号通过Intent传递过去
                try {
                    if (!bindService(new Intent("hk.cic.cwrs.bio.integration.log.IBioService"),
                            conLog, BIND_AUTO_CREATE)) {
                    }
                } catch (Exception e) {
                    L.printException(e);
                }
                if (bLog) {
                    try {
                        ibioService.ResultLog(strDetail);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void getWorkerDetails(final String SessionId, final String CWRNo) {
        new Thread() {
            @Override
            public void run() {
                try {
                    ParamBaseBean.BgDataBean<String> bgDataBean = new ParamBaseBean.BgDataBean<String>();

                    bgDataBean.setActionType("getallworker");

                    bgDataBean.setClientVersion("1.0");

                    bgDataBean.setData("");

                    ParamBaseBean paramBaseBean = new ParamBaseBean();

                    paramBaseBean.setBgdata(bgDataBean);

                    String url = getHostUrl();

                    String postJson = paramBaseBean.toJsonParam(paramBaseBean);

                    String res = new HttpPost().HttpRequestAPI(url + "iGetData.ashx","POST", postJson);


                    L.i("IcService", "getWorkerDetails--->" + res);

                    if (res != null && res.length() > 0) {

                        try {

                            WorkerDetailsParamBean bean = JSON.parseObject(res, WorkerDetailsParamBean.class);

                            if (bean == null) {

                                mHandler.sendEmptyMessage(MSG_GET_WORKER_DETAILES_FAILED);

                            } else {

                                //TODO

                                //                                if (bean.getBgdata() != null && bean.getBgdata().getData() != null){

                                //

                                //                                }else{

                                //                                    mHandler.sendEmptyMessage(MSG_GET_WORKER_DETAILES_FAILED);

                                //                                }

                            }

                        } catch (Exception e) {

                            L.printException(e);

                            mHandler.sendEmptyMessage(MSG_GET_WORKER_DETAILES_FAILED);

                        }

                    } else {

                        mHandler.sendEmptyMessage(MSG_GET_WORKER_DETAILES_FAILED);

                    }

                } catch (Exception e) {

                    L.printException(e);

                }

            }

        }.start();

    }

    private ServiceConnection conLog = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder server) {
            ibioService = IBioService.Stub.asInterface(server);
            bLog = true;
        }

        public void onServiceDisconnected(ComponentName name) {
            bLog = false;
        }
    };

    public String getHostUrl(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("server_host", "");
    }

    public int getIsFace() {
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getInt("is_face", 0);
    }


    private final int MSG_GET_WORKER_DETAILES_FAILED = 11;
    Intent intentFaceCheckResultActivity;
    private void openCheckInOutView(Context context, String cwrNo) {
        if(intentFaceCheckResultActivity == null) {
            intentFaceCheckResultActivity = new Intent(context,CheckInOrOutActivity.class);
        }
        intentFaceCheckResultActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //用Bundle携带数据
        Bundle bundle=new Bundle();
        //传递name参数为tinyphp
        bundle.putString("cwrNo", cwrNo);
        intentFaceCheckResultActivity.putExtras(bundle);
        context.startActivity(intentFaceCheckResultActivity);
    }

    private void openFaceCheckResulterView(Context context, String cwrNo) {
        if(intentFaceCheckResultActivity == null) {
            intentFaceCheckResultActivity = new Intent(context,FaceCheckResultActivity.class);
        }
        //  Intent intent = new Intent(context,TestActivity.class);
        intentFaceCheckResultActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //用Bundle携带数据
        Bundle bundle=new Bundle();
        //传递name参数为tinyphp
        bundle.putString("cwrNo", cwrNo);
        intentFaceCheckResultActivity.putExtras(bundle);
        context.startActivity(intentFaceCheckResultActivity);
    }
    Intent intentJustCheckActivity ;
    private void justCheckResulterView(Context context, String cwrNo) {
        if(intentJustCheckActivity == null) {
            intentJustCheckActivity = new Intent(context,JustCheckActivity.class);
        }

        intentJustCheckActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //用Bundle携带数据
        Bundle bundle=new Bundle();
        //传递name参数为tinyphp
        bundle.putString("cwrNo", cwrNo);
        intentJustCheckActivity.putExtras(bundle);
        context.startActivity(intentJustCheckActivity);
    }

}
